package com.changer.common.service.impl;

import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.changer.common.service.MobileService;
import com.changer.framework.util.HttpUtils;
import com.changer.framework.util.JsonUtils;

/**
 * @author Jiwei Guo
 *
 */
@Service
public class YunPianMobileService implements MobileService{

	private static final Logger LOGGER = LoggerFactory.getLogger(YunPianMobileService.class);
	
	private final static String API_KEY = "7f250938c137a9685f4a6fe8dbe99a96";
		
	private final static String URI_SEND_SMS = "http://yunpian.com/v1/sms/send.json";
	
	private static final Map<String, String> CODE_MSG = new HashMap<String, String>();
	
	static{
		CODE_MSG.put("1", "补充必须传入的参数");
		CODE_MSG.put("2", "按提示修改参数值的格式");
		CODE_MSG.put("3", "账户余额不足");
		CODE_MSG.put("4", "关键词屏蔽");
		CODE_MSG.put("5", "未找到对应id的模板");
		CODE_MSG.put("6", "添加模板失败");
		CODE_MSG.put("7", "模板不可用");
		CODE_MSG.put("8", "同一手机号30秒内重复提交相同的内容");
		CODE_MSG.put("9", "同一手机号5分钟内重复提交相同的内容超过3次");
		CODE_MSG.put("10", "手机号黑名单过滤");
		CODE_MSG.put("11", "接口不支持GET方式调用");
		CODE_MSG.put("12", "接口不支持POST方式调用");
		CODE_MSG.put("13", "营销短信暂停发送");
		CODE_MSG.put("14", "解码失败");
		CODE_MSG.put("15", "签名不匹配");
		CODE_MSG.put("16", "签名格式不正确");
		CODE_MSG.put("17", "24小时内同一手机号发送次数超过限制");
		
		CODE_MSG.put("-1", "非法的apikey");
		CODE_MSG.put("-2", "API没有权限");
		CODE_MSG.put("-3", "IP没有权限");
		CODE_MSG.put("-4", "访问次数超限");
		CODE_MSG.put("-5", "访问频率超限");
		
		CODE_MSG.put("-50", "未知异常");
		CODE_MSG.put("-51", "系统繁忙");
		CODE_MSG.put("-52", "充值失败");
		CODE_MSG.put("-53", "提交短信失败");
		CODE_MSG.put("-54", "记录已存在");
		CODE_MSG.put("-55", "记录不存在");
		CODE_MSG.put("-57", "用户开通过固定签名功能，但签名未设置");
	}
	    
	public String send(String mobile, String content) throws Exception {
		Map<String, String> params = new HashMap<String, String>();
        params.put("apikey", API_KEY);
        params.put("text", content);
        params.put("mobile", mobile);
        String json = HttpUtils.post(URI_SEND_SMS, params);
        String code = JsonUtils.getValue(json, "code").toString();
        if(code.equals("0")){
        	//NOP
        } else if(CODE_MSG.containsKey(code)){
        	String msg = CODE_MSG.get(code);
        	LOGGER.error("error code : " + code + " , msg : " + msg);
        } else{
        	LOGGER.error("unknow code : " + code);
        }
		return code;
	}
	
	
}
